﻿/// <summary>
/// https://leetcode-cn.com/problems/swap-nodes-in-pairs/
/// </summary>
public class Solution
{
    public ListNode SwapPairs(ListNode head)
    {
        Queue<ListNode> even = new Queue<ListNode>();
        Queue<ListNode> odd = new Queue<ListNode>();

        int length = 0;
        for (var current = head; current != null; length++, current = current.next)
        {
            if (length % 2 == 0)
                even.Enqueue(current);
            else
                odd.Enqueue(current);
        }

        if (length is 0 or 1)
            return head;

        var result = odd.Dequeue();

        {
            var current = result;
            current.next = null;
            for (; ; )
            {
                if (!even.TryDequeue(out current.next))
                    break;
                current = current.next;
                current.next = null;

                if (!odd.TryDequeue(out current.next))
                    continue;
                current = current.next;
                current.next = null;
            }
        }

        return result;
    }
}